// 多图片上传云存储
<template>
  <div>
    <label for="upload">
      选择图片上传
    </label>
    <input
      @change="onChange"
      ref="file"
      type="file"
      multiple
      id="upload"
      style="display: none;"
      accept="image/*tr"
    />
    <p class="tip">提示： 一次可选择多张图片，最多不超过9张</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      client: new OSS({
        region: '', // 云的存储路线选择
        bucket: '', //bucket名称
        accessKeyId: ACCESSKEY.ID,
        accessKeySecret: ACCESSKEY.SECRET,
      }),
      imgList: [],
      isUploading: false,
    }
  },
  methods: {
    onChange() {
      //可选链
      const newFiles = this.$refs?.file?.newFiles
      //校验
      if (newFiles.length > 9) {
        alert('最多可以一次选择9张图片')
        return false
      }

      const files = []
      for (const file of newFiles) {
        const size = file.size / 1024 / 1024
        if (size > 1) {
          alert('请选择1m以内的图片')
          return false
        }
        files.push(file)
      }
      this.uploadFilesByOss()
    },

    uploadFilesByOss(files) {
      this.isUploading = true
      const uploadRequest = []
      for (const file of files) {
        uploadRequest.push(
          new Promise((resolve, reject) => {
            //上传文件名称
            this.client
              .put(`${Math.random()}-${file.name}`, file)
              .then((res) => {
                console.log(res)
                this.imgList = [...this.imgList, res.url] // 显示顺序不确定
                resolve()
              })
              .catch((err) => {
                console.log(err)
                reject()
              })
          }),
        )
      }
      // Promise.all(uploadRequest).then(res => {
      Promise.allSettled(uploadRequest)
        .then((res) => {
          const imgs = []
          for (const item of res) {
            if (item.status === 'fulfilled') {
              imgs.push(item.value)
            }
          }
          this.imgList = res
          console.log(res)
        })
        .catch((err) => {
          console.log(err)
        })
        .finally(() => {
          this.isUploading = false
        })
    },
  },
}
</script>

<style lang="scss" scoped></style>
